package servlet.books;

import com.alibaba.fastjson.JSONObject;
import utils.JdbcUtil;
import utils.ResultData;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * 删除图书
 */
@WebServlet(urlPatterns = "/booksDelete")
public class BooksDelete extends HttpServlet {
    JdbcUtil jdbcUtil = new JdbcUtil();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //获取id
        String ids = req.getParameter("id");
        //打开jdbc连接
        Connection connection = jdbcUtil.getConnection();
        String[] split = ids.split(",");
        int i = 0;
        for (String idStr : split) {
            //删除图书
            String sql = "delete from book_manage where id = ?";
            try {
                PreparedStatement preparedStatement = connection.prepareStatement(sql);
                //设置参数
                preparedStatement.setInt(1, Integer.valueOf(idStr));
                //执行sql语句
                i += preparedStatement.executeUpdate();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        //返回数据给前端
        ResultData resultData;
        if (i == split.length) {
            resultData = ResultData.success();
        } else {
            resultData = ResultData.fail();
        }
        Object o = JSONObject.toJSON(resultData);
        resp.getWriter().print(o.toString());
    }
}

